import React, { useState, useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { motion } from 'framer-motion';
import { useAuth } from '../contexts/AuthContext';
import { creditsService, UserCredits } from '../services/credits';

import DesignPreview from '../components/DesignPreview';
import DesignStatistics from '../components/DesignStatistics';
import DesignGallery from '../components/DesignGallery';
import BillingManagement from '../components/BillingManagement';
import CreateDesign from '../components/CreateDesign';
import TextToImageDesign from '../components/TextToImageDesign';
import seaImage from '../images/sea.png';
import tribalImage from '../images/Tribal.png';
import Professional from '../images/Professional.png';
import Bohemian from '../images/Bohemian.jpg';
import Minimalist from '../images/Minimalist.jpg';
import Industrial from '../images/Industrial.jpg';
import Cyberpunk from '../images/Cyberpunk.jpg';
import Scandinavian from '../images/Scandinavian.jpg';

interface UserProfile {
  name: string;
  email?: string;
  credits?: number;
}

const Profile: React.FC = () => {
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [userCredits, setUserCredits] = useState<UserCredits | null>(null);
  const [activeTab, setActiveTab] = useState('profile');
  const { user, isAuthenticated, isLoading: authLoading, logout } = useAuth();
  const history = useHistory();
  
  // Design related states
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [processedImage, setProcessedImage] = useState<string | null>(null);
  const [selectedStyle, setSelectedStyle] = useState<string>('modern');
  const [selectedRoomType, setSelectedRoomType] = useState<string>('living-room');
  const [isProcessing, setIsProcessing] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  // Gallery and billing related states - moved to respective components

  
  // Stats related states - moved to DesignStatistics component

  useEffect(() => {
    if (!authLoading) {
      if (!isAuthenticated || !user) {
        history.push('/login');
        return;
      }

      // 使用AuthContext中的用户信息
      setProfile({
        name: user.firstName && user.lastName ? `${user.firstName} ${user.lastName}` : user.email,
        email: user.email,
        credits: parseInt(localStorage.getItem('credits') || '0'),
      });
    }
  }, [isAuthenticated, user, authLoading, history]);

  useEffect(() => {
    const loadUserCredits = async () => {
      if (user) {
        try {
          const credits = await creditsService.getUserCredits(user.id);
          setUserCredits(credits);
        } catch (error) {
          console.error('Failed to load credits:', error);
          setUserCredits(null);
        }
      }
    };

    loadUserCredits();
  }, [user]);

  // Design loading moved to respective components
  
  // loadDesignStats function moved to DesignStatistics component

  const handleLogout = async () => {
    try {
      await logout();
      history.push('/');
    } catch (error) {
      console.error('登出失败:', error);
      history.push('/');
    }
  };

  const getUserDisplayName = () => {
    if (user?.firstName && user?.lastName) {
      return `${user.firstName} ${user.lastName}`;
    }
    if (user?.firstName) {
      return user.firstName;
    }
    if (user?.email) {
      return user.email.split('@')[0];
    }
    return 'User';
  };

  const getUserAvatarLetter = () => {
    const displayName = getUserDisplayName();
    return displayName.charAt(0).toUpperCase();
  };

  if (authLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-blue-500 border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading your profile...</p>
        </div>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl text-gray-700">Could not load profile information.</p>
          <button
            onClick={() => history.push('/login')}
            className="mt-4 px-6 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors"
          >
            Go to Login
          </button>
        </div>
      </div>
    );
  }

  const menuItems = [
    {
      id: 'profile',
      name: 'Profile',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
        </svg>
      ),
    },
    {
      id: 'designs',
      name: 'Create Design',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
      ),
    },
    {
      id: 'text-to-image',
      name: 'Text Design',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
        </svg>
      ),
    },
    {
      id: 'gallery',
      name: 'Design Gallery',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
        </svg>
      ),
    },
    {
      id: 'stats',
      name: 'Design Statistics',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v4a2 2 0 01-2 2h-2a2 2 0 00-2-2z" />
        </svg>
      ),
    },
    {
      id: 'billing',
      name: 'Billing',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
        </svg>
      ),
    },
  ];

  // Design related functions
  const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (!file.type.match('image.*')) {
        return;
      }
      if (file.size > 10 * 1024 * 1024) {
        return;
      }
      const reader = new FileReader();
      reader.onloadstart = () => setUploadProgress(0);
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          setUploadProgress(progress);
        }
      };
      reader.onloadend = () => {
        setUploadProgress(100);
        setSelectedImage(reader.result as string);
        setProcessedImage(null);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
  };

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
    const file = event.dataTransfer.files[0];
    if (file) {
      if (!file.type.match('image.*')) {
        return;
      }
      if (file.size > 10 * 1024 * 1024) {
        return;
      }
      const reader = new FileReader();
      reader.onloadstart = () => setUploadProgress(0);
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          setUploadProgress(progress);
        }
      };
      reader.onloadend = () => {
        setUploadProgress(100);
        setSelectedImage(reader.result as string);
        setProcessedImage(null);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleGenerate = async () => {
    // 检查是否有选择文件
    if (!fileInputRef.current?.files?.[0]) {
      return;
    }
    
    // 检查用户积分
    if (!userCredits || userCredits.creditBalance < 1) {
      history.push('/buy-credits');
      return;
    }
    
    setIsProcessing(true);
    try {
      // 直接使用原始文件对象
      const file = fileInputRef.current.files[0];
      const prompt = `Design ${selectedRoomType} in ${selectedStyle} style`;
      
      // 调用API创建设计
      const { createDesign, getDesignStatus } = await import('../services/design');
      const response = await createDesign({
        roomType: selectedRoomType,
        designStyle: selectedStyle,
        prompt: prompt,
        file: file
      });
      
      if (response.success && response.data.id) {
        // Task created successfully, now poll for completion
        const taskId = response.data.id;
        
        // Update credits immediately
        if (user) {
          try {
            const updatedCredits = await creditsService.getUserCredits(user.id);
            setUserCredits(updatedCredits);
          } catch (error) {
            console.error('Failed to refresh credits:', error);
          }
        }
        
        // Poll for task completion
        const pollInterval = setInterval(async () => {
          try {
            const statusData = await getDesignStatus(taskId);
            
            if (statusData.success) {
              if (statusData.data.status === 'completed' && statusData.data.generatedImageUrl) {
                clearInterval(pollInterval);
                setProcessedImage(statusData.data.generatedImageUrl);
                setIsProcessing(false);
              } else if (statusData.data.status === 'failed') {
                clearInterval(pollInterval);
                setIsProcessing(false);
                console.error('Design generation failed: ' + (statusData.data.errorMessage || 'Unknown error'));
              }
            }
          } catch (pollError) {
            console.error('Error polling task status:', pollError);
          }
        }, 3000);
        
        // Set timeout
        setTimeout(() => {
          clearInterval(pollInterval);
          if (isProcessing) {
            setIsProcessing(false);
            console.error('Design generation timed out. Please try again.');
          }
        }, 300000);
      } else {
        throw new Error(response.message || '生成设计失败');
      }
    } catch (error) {
      console.error('处理图片时出错:', error);
    } finally {
      setIsProcessing(false);
    }
  };

  const roomTypes = [
    { id: 'living-room', name: 'Living Room' },
    { id: 'bedroom', name: 'Bedroom' },
    { id: 'kitchen', name: 'Kitchen' },
    { id: 'bathroom', name: 'Bathroom' },
    { id: 'office', name: 'Office' },
    { id: 'dining-room', name: 'Dining Room' },
    { id: 'game-room', name: 'Game Room' },
    { id: 'basement', name: 'Basement' },
    { id: 'outdoor-terrace', name: 'Outdoor Terrace' },
  ];

  const designStyles = [
    { id: 'modern', name: 'Modern', image: 'https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80' },
    { id: 'minimalist', name: 'Minimalist', image: Minimalist },
    { id: 'scandinavian', name: 'Scandinavian', image: Scandinavian },
    { id: 'industrial', name: 'Industrial', image: Industrial },
    { id: 'bohemian', name: 'Bohemian', image: Bohemian },
    { id: 'tribal', name: 'Tribal', image: tribalImage },
    { id: 'cyberpunk', name: 'Cyberpunk', image: Cyberpunk },
    { id: 'coastal', name: 'Coastal', image: seaImage },
    { id: 'professional', name: 'Professional', image: Professional },
  ];





  const renderContent = () => {
    switch (activeTab) {
      case 'designs':
        return (
          <CreateDesign 
            onDesignCreated={(imageUrl) => {
              // Handle design creation success
              console.log('Design created:', imageUrl);
            }}
            onCreditsUpdated={() => {
              // Refresh user credits
              if (user) {
                creditsService.getUserCredits(user.id)
                  .then(credits => setUserCredits(credits))
                  .catch(error => console.error('Failed to refresh credits:', error));
              }
            }}
          />
        );
      case 'text-to-image':
        return (
          <TextToImageDesign 
            onDesignCreated={(imageUrl) => {
              // Handle design creation success
              console.log('Text design created:', imageUrl);
            }}
            onCreditsUpdated={() => {
              // Refresh user credits
              if (user) {
                creditsService.getUserCredits(user.id)
                  .then(credits => setUserCredits(credits))
                  .catch(error => console.error('Failed to refresh credits:', error));
              }
            }}
          />
        );
      case 'profile':
        return (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="space-y-6"
          >
            {/* 用户信息卡片 */}
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
              <div className="bg-gradient-to-r from-blue-600 to-indigo-700 p-8">
                <div className="flex items-center space-x-4">
                  <div className="w-24 h-24 rounded-full bg-gradient-to-tr from-blue-400 via-purple-300 to-blue-200 p-1 flex items-center justify-center">
                    <div className="w-full h-full rounded-full bg-white flex items-center justify-center text-4xl font-bold text-blue-500 shadow-lg">
                      {getUserAvatarLetter()}
                    </div>
                  </div>
                  <div className="flex-1">
                    <h1 className="text-2xl font-bold text-white mb-2">
                      {getUserDisplayName()}
                    </h1>
                    <p className="text-blue-100 text-lg">
                      {user?.email}
                    </p>
                  </div>
                </div>
              </div>
              
              <div className="p-8">
                <div className="grid grid-cols-2 gap-8 mt-8">
                  <div className="bg-gradient-to-tr from-blue-100 via-blue-200 to-purple-100 rounded-xl shadow-lg p-8 flex flex-col items-center animate-fadeIn">
                    <div className="text-5xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-blue-500 to-purple-500 animate-pulse">{userCredits?.creditBalance || 0}</div>
                    <div className="text-lg text-gray-600 mt-2">Credit Balance</div>
                     </div>
                  <div className="bg-gradient-to-tr from-blue-100 via-blue-200 to-purple-100 rounded-xl shadow-lg p-8 flex flex-col items-center animate-fadeIn">
                    <div className="text-5xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-blue-500 to-purple-500 animate-pulse">{userCredits && userCredits.expiresAt ? (userCredits.daysUntilExpiration || 0) : '∞'}</div>
                    <div className="text-lg text-gray-600 mt-2">Days Remaining</div>
                   </div>
                 </div>
              </div>
            </div>

            {/* 账户设置 */}
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-8">
              <h2 className="text-xl font-semibold text-gray-900 mb-6">Account Settings</h2>
              <div className="space-y-4">
                <div className="flex items-center justify-between py-4 border-b border-gray-200">
                  <div>
                    <h3 className="font-medium text-gray-900">Email Address</h3>
                    <p className="text-sm text-gray-600">{user?.email}</p>
                  </div>
                  <button className="px-4 py-2 text-sm font-medium text-blue-600 hover:text-blue-700 transition-colors">
                    Edit
                  </button>
                </div>
                <div className="flex items-center justify-between py-4 border-b border-gray-200">
                  <div>
                    <h3 className="font-medium text-gray-900">Password</h3>
                    <p className="text-sm text-gray-600">Last modified 30 days ago</p>
                  </div>
                  <button className="px-4 py-2 text-sm font-medium text-blue-600 hover:text-blue-700 transition-colors">
                    Edit
                  </button>
                </div>
                <div className="flex items-center justify-between py-4">
                  <div>
                    <h3 className="font-medium text-gray-900">Two-Factor Authentication</h3>
                    <p className="text-sm text-gray-600">Enhance account security</p>
                  </div>
                  <button className="px-4 py-2 text-sm font-medium text-blue-600 hover:text-blue-700 transition-colors">
                    Enable
                  </button>
                </div>
              </div>
            </div>
          </motion.div>
        );
      case 'gallery':
        return <DesignGallery onCreateDesign={() => setActiveTab('designs')} />;
      case 'billing':
        return <BillingManagement userCredits={userCredits} />;
      case 'stats':
        return <DesignStatistics onCreateDesign={() => setActiveTab('designs')} />;

      case 'profile':
        return (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="space-y-6"
          >
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 md:p-8">
              <div className="flex flex-col sm:flex-row items-start sm:items-center space-y-4 sm:space-y-0 sm:space-x-6">
                <div className="w-20 h-20 bg-blue-500 rounded-full flex items-center justify-center text-white text-2xl font-bold">
                  {getUserAvatarLetter()}
                </div>
                <div className="flex-1">
                  <h1 className="text-2xl font-bold text-gray-900">{getUserDisplayName()}</h1>
                  <p className="text-gray-600">{user?.email}</p>
                  <div className="mt-2 flex flex-wrap gap-4">
                    <div className="text-sm">
                      <span className="text-gray-500">Credit Balance:</span>
                      <span className="ml-1 font-semibold text-blue-600">
                        {userCredits?.creditBalance || 0}
                      </span>
                    </div>
                    <div className="text-sm">
                      <span className="text-gray-500">Expires:</span>
                      <span className="ml-1 font-semibold text-gray-900">
                        {userCredits?.expiresAt ? new Date(userCredits.expiresAt).toLocaleDateString('en-US') : 'Never'}
                      </span>
                    </div>
                  </div>
                </div>
                <button
                  onClick={() => history.push('/buy-credits')}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  Buy Credits
                </button>
              </div>
            </div>
          </motion.div>
        );
      case 'text-to-image':
        return (
          <TextToImageDesign 
            onDesignCreated={(imageUrl) => {
              // Handle design creation success
              console.log('Text design created:', imageUrl);
            }}
            onCreditsUpdated={() => {
              // Refresh user credits
              if (user) {
                creditsService.getUserCredits(user.id)
                  .then(credits => setUserCredits(credits))
                  .catch(error => console.error('Failed to refresh credits:', error));
              }
            }}
          />
        );
      
      case 'stats':
        return (
          <DesignStatistics onCreateDesign={() => setActiveTab('designs')} />
        );
      case 'text-to-image':
        return (
          <TextToImageDesign 
            onDesignCreated={(imageUrl) => {
              // Handle design creation success
              console.log('Text design created:', imageUrl);
            }}
            onCreditsUpdated={() => {
              // Refresh user credits
              if (user) {
                creditsService.getUserCredits(user.id)
                  .then(credits => setUserCredits(credits))
                  .catch(error => console.error('Failed to refresh credits:', error));
              }
            }}
          />
        );
      
      case 'billing':
        return (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="space-y-6"
          >
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 md:p-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">Billing Management</h2>
              
              {/* 账户概览 */}
              <div className="grid grid-cols-3 gap-3">
                <div className="bg-gradient-to-r from-indigo-500 to-indigo-600 rounded-lg p-6 text-white">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-indigo-100 text-sm">Current Balance</p>
                      <p className="text-3xl font-bold">{userCredits?.creditBalance || 0}</p>
                      <p className="text-indigo-200 text-xs mt-1">Credits</p>
                    </div>
                    <svg className="w-8 h-8 text-indigo-200" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4z"/>
                      <path fillRule="evenodd" d="M18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z" clipRule="evenodd"/>
                    </svg>
                  </div>
                </div>
                
                <div className="bg-gradient-to-r from-emerald-500 to-emerald-600 rounded-lg p-6 text-white">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-emerald-100 text-sm">Days remaining</p>
                      <p className="text-3xl font-bold">{userCredits?.daysUntilExpiration || '∞'}</p>
                      <p className="text-emerald-200 text-xs mt-1">Days</p>
                    </div>
                    <svg className="w-8 h-8 text-emerald-200" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M10 2a4 4 0 00-4 4v1H5a1 1 0 00-.994.89l-1 9A1 1 0 004 18h12a1 1 0 00.994-1.11l-1-9A1 1 0 0015 7h-1V6a4 4 0 00-4-4zm2 5V6a2 2 0 10-4 0v1h4zm-6 3a1 1 0 112 0 1 1 0 01-2 0zm7-1a1 1 0 100 2 1 1 0 000-2z" clipRule="evenodd"/>
                    </svg>
                  </div>
                </div>
                
                <div className="bg-gradient-to-r from-rose-500 to-rose-600 rounded-lg p-6 text-white">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-rose-100 text-sm">Status</p>
                      <p className="text-3xl font-bold">{userCredits?.isExpired ? 'Expired' : 'Active'}</p>
                      <p className="text-rose-200 text-xs mt-1">Credit Status</p>
                    </div>
                    <svg className="w-8 h-8 text-rose-200" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clipRule="evenodd"/>
                    </svg>
                  </div>
                </div>
              </div>
              

            </div>
          </motion.div>
        );
      case 'text-to-image':
        return (
          <TextToImageDesign 
            onDesignCreated={(imageUrl) => {
              // Handle design creation success
              console.log('Text to image design created:', imageUrl);
            }}
            onCreditsUpdated={() => {
              // Refresh user credits
              if (user) {
                creditsService.getUserCredits(user.id)
                  .then(credits => setUserCredits(credits))
                  .catch(error => console.error('Failed to refresh credits:', error));
              }
            }}
          />
        );
      
      default:
        return (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="text-center py-12"
          >
            <h3 className="text-lg font-medium text-gray-900 mb-2">Coming Soon</h3>
            <p className="text-gray-600">This feature is under development</p>
          </motion.div>
        );
      case 'text-to-image':
        return (
          <TextToImageDesign 
            onDesignCreated={(imageUrl) => {
              // Handle design creation success
              console.log('Text to image design created:', imageUrl);
            }}
            onCreditsUpdated={() => {
              // Refresh user credits
              if (user) {
                creditsService.getUserCredits(user.id)
                  .then(credits => setUserCredits(credits))
                  .catch(error => console.error('Failed to refresh credits:', error));
              }
            }}
          />
        );
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex flex-col xl:flex-row gap-6 lg:gap-8">
          {/* Left Menu */}
          <div className="xl:w-80 flex-shrink-0">
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
              {/* Menu Header */}
              <div className="p-6 border-b border-gray-200 bg-gradient-to-r from-blue-100 via-blue-200 to-blue-300 text-blue-900 rounded-t-xl">
                <h2 className="text-lg font-semibold tracking-wide">Personal Center</h2>
              </div>
              
              {/* Menu Items */}
              <nav className="p-2">
                {menuItems.map((item) => (
                  <button
                    key={item.id}
                    onClick={() => setActiveTab(item.id)}
                    className={`w-full flex items-center space-x-3 px-4 py-3 rounded-lg text-left transition-all duration-200 ${
                      activeTab === item.id
                        ? 'bg-blue-50 text-blue-700 border-l-4 border-blue-600'
                        : 'text-gray-700 hover:bg-gray-50 hover:text-gray-900'
                    }`}
                  >
                    <div className={`flex-shrink-0 ${
                      activeTab === item.id ? 'text-blue-600' : 'text-gray-400'
                    }`}>
                      {item.icon}
                    </div>
                    <span className="font-medium">{item.name}</span>
                  </button>
                ))}
                
                {/* Logout */}
                <div className="border-t border-gray-200 mt-4 pt-4">
                  <button
                    onClick={handleLogout}
                    className="w-full flex items-center space-x-3 px-4 py-3 rounded-lg text-left bg-gray-100 text-red-500 font-bold shadow hover:bg-red-50 hover:border hover:border-red-400 hover:scale-105 transition-all duration-200"
                  >
                    <svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                    </svg>
                    <span className="font-medium">Logout</span>
                  </button>
                </div>
              </nav>
            </div>
          </div>

          {/* Right Content Area */}
          <div className="flex-1 min-w-0">
            {renderContent()}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Profile;